import axios from 'axios';

const http = axios.create({
	baseURL: '/', // api 的 base_url
	timeout: 30000, // request timeout
	headers: {// 默认的
		'Content-Type': 'application/json'
	},
	responseType: 'json', // 默认的
})

http.interceptors.request.use(
	config => {
		return config
	},
	error => {
		// Do something with request error
		console.log(error) // for debug
		Promise.reject(error)
	}
)

// response interceptor
http.interceptors.response.use(
	response => {
		return response
	},
	error => {
		console.log(error)
		return Promise.reject(error)
	}
)

let configuration = {
	loading:(isOpen)=>{
		console.log("default http loading =>" + isOpen);
	},
	before: (object) => {
		console.log("default http before" +JSON.stringify(object));
	},
	after: (response) => {
		console.log("default http before after");
		return response;
	},
	timeout:() => {
		console.log("default http before timeout");
	}
}

export default {
	configuration: function(config){
		configuration.loading = config.loading != null ? config.loading:configuration.loading;
		configuration.before = config.before != null ? config.before:configuration.before;
		configuration.after = config.after != null ? config.after:configuration.after;
		configuration.timeout = config.timeout != null ? config.timeout:configuration.timeout;
	},
	post: function(URI, data, headObject = {}, t = -1) {
		if(URI.LOADING && typeof(configuration.before) == 'function') {
			configuration.loading(true);
		}
		let header =  {"Accept": "application/json","Content-Type": "application/json"};
		headObject = {...header,...headObject};		
		return new Promise((resolve,reject) => {			
			let timeOutId = setTimeout(()=>{
				if(URI.LOADING && typeof(configuration.after) == 'function') {
					configuration.loading(false);
				}
				reject({'message':' time out'});
			},5000);
			//console.log("URI=>" + URI.ACTION + "==>" + JSON.stringify(data) + "NAME=>" + URI.NAME);
			http({ url: URI.ACTION, method: "post", data: data, headers:headObject}).then((response) => {
				clearTimeout(timeOutId);
				if(URI.LOADING && typeof(configuration.after) == 'function') {
					configuration.loading(false);
				}
				resolve(response.data);				
			}).catch((response) => {
				if(URI.LOADING && typeof(configuration.after) == 'function') {
					configuration.loading(false);
				}
				clearTimeout(timeOutId);
				reject(response.data);
			});
		});
	},
	get: function() {
		
	}
}